package com.atguigu.lease.web.app.service.impl;

import com.atguigu.lease.common.constant.RedisConstant;
import com.atguigu.lease.common.exception.LeaseException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.common.utils.CodeUtil;
import com.atguigu.lease.common.utils.JwtUtil;
import com.atguigu.lease.model.entity.UserInfo;
import com.atguigu.lease.model.enums.BaseStatus;
import com.atguigu.lease.web.app.mapper.UserInfoMapper;
import com.atguigu.lease.web.app.service.LoginService;
import com.atguigu.lease.web.app.service.SmsService;
import com.atguigu.lease.web.app.vo.user.LoginVo;
import com.atguigu.lease.web.app.vo.user.UserInfoVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private SmsService smsservice;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private UserInfoMapper userInfoMapper;
    /**
     * 每分钟1条验证码信息：：：：：实现存入之前先查一下redis有没有这个手机号
     * @param phone
     */
    @Override
    public void getCode(String phone) {
        //生产随机验证码    获取key
        String code = CodeUtil.getRandomCode(6);
        String key = RedisConstant.APP_LOGIN_PREFIX +phone;
        //传人电话和code 将他放到redis中
        smsservice.sendCode(phone,code);
        //redisTemplate.hasKey(key)函数是判断收否存在这个key   存在返回true 不存在返回false
        Boolean b = redisTemplate.hasKey(key);
        if (b){
            //redisTemplate.getExpire返回这个key存在的时间
            Long ttl = redisTemplate.getExpire(key, TimeUnit.SECONDS);
            //如果60-ttl小于一分钟就不发短信
            if (RedisConstant.APP_LOGIN_CODE_RESEND_TIME_SEC-ttl <RedisConstant.APP_LOGIN_CODE_TTL_SEC){
                throw new LeaseException(ResultCodeEnum.APP_SEND_SMS_TOO_OFTEN);
            }
        }
        //将他存入redis数据库中
        redisTemplate.opsForValue().set(key,code,RedisConstant.ADMIN_LOGIN_CAPTCHA_TTL_SEC, TimeUnit.SECONDS);
    }

    /**
     * 用户登录
     * @param loginVo
     * @return
     */
    @Override
    public String login(LoginVo loginVo) {
        //判断手机号是否为空
        if (loginVo.getPhone() == null){
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_PHONE_EMPTY);
        }
        //判断验证码为空
        if (loginVo.getCode() == null){
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_CODE_EMPTY);
        }
        //从redis查询验证码b     并判断code是否为null
        String key = RedisConstant.APP_LOGIN_PREFIX + loginVo.getPhone();
        String code = (String) redisTemplate.opsForValue().get(key);
        if (code == null){
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_CODE_EMPTY);
        }
        //如果不为空就把redis里面的code与VO里面的code进行比较
        if (!code.equals(loginVo.getCode())){
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_CODE_ERROR);
        }
        //g根据手机号查询用户信息
        LambdaQueryWrapper<UserInfo> quryWrapper = new LambdaQueryWrapper<>();
        quryWrapper.eq(UserInfo::getPhone,loginVo.getPhone());
        UserInfo userInfo = userInfoMapper.selectOne(quryWrapper);   //获取用户信息
        // 用户信息如果为空就注册，如果老用户就判断是否被禁用 ，在最后登录
        if(userInfo == null){
            //注册
            userInfo = new UserInfo();
            userInfo.setPhone(loginVo.getPhone());
            userInfo.setStatus(BaseStatus.ENABLE);
            userInfo.setNickname("用户"+loginVo.getPhone().substring(7));
            userInfoMapper.insert(userInfo);
        }else {
            //判断是否被禁用
            if (userInfo.getStatus() == BaseStatus.DISABLE){
                throw new LeaseException(ResultCodeEnum.APP_ACCOUNT_DISABLED_ERROR);
            }
        }

        //返回jwt
        return JwtUtil.createToken(userInfo.getId(),userInfo.getPhone());
    }

    /**
     * 根据id获取user信息
     * @param userId
     * @return
     */
    @Override
    public UserInfoVo getLoginUserById(Long userId) {
        UserInfo userInfo = userInfoMapper.selectById(userId);
        UserInfoVo userInfoVo = new UserInfoVo(userInfo.getNickname(),userInfo.getAvatarUrl());
        return userInfoVo;
    }
}
